home *** CD-ROM | disk | FTP | other *** search
- Path: news.iag.net!news
- From: jatmon@iag.net (John R Buchan)
- Newsgroups: comp.lang.c,comp.lang.objective-c
- Subject: Re: Comma Delimited function wanted
- Date: 12 Jan 1996 17:16:49 GMT
- Organization: Internet Access Group, Orlando, Florida
- Message-ID: <4d6521$g4r@news.iag.net>
- References: <4d1l42$mb6@voyager.Internex.NET> <4d3360$kg3@tahko.lpr.carel.fi>
- NNTP-Posting-Host: pm1-orl25.iag.net
- X-Newsreader: WinVN 0.99.7
-
- In article <4d3360$kg3@tahko.lpr.carel.fi>, aril@cmt.lpr.mail.carel.fi says...
- >
- <snip>
- >Try something like this:
-
- You didn't try your own code first, did you <scowling fiercely>. :-)
- Anyway, it will need a few modifications to work at all and a few more to
- work safely. See the rewrite below.
-
- >
- > char buffer[] = "1,2,3,4"; /* Just an example */
- > char *p = buffer; /* points to begin of buf */
- > char field[4][20];
- > int i, j;
- >
- > for (j = 0; j < 4; j++) {
- > memset(field[j], 0, sizeof(field[j])); /* Initialize to
- zeros */
- > for (i = 0; i < sizeof(field[j]); i++, p++)
- > if (*p == ',' || !*p) {
- > field[j][i] = '\0';
- > break;
- > }
- > else
- > field[j][i] = *p;
- > }
- >
-
- #include <stdio.h>
- #include <string.h>
-
- int main(void)
- {
- char buffer[] = "123,,4,"; /* Make it a bit harder */
- char *p = buffer; /* points to begin of buf */
- char field[4][20];
- int i, j;
-
- for (j = 0; j < 4; j++)
- {
- /* memset(field[j], 0, sizeof(field[j])); ?? not necessary. */
- for (i = 0; i <= sizeof(field[j]); i++, p++) /* allow for '\0' */
- if( *p == ',' || !*p) /* these conditions could be added to the */
- break; /* for statement to eliminate these three */
- else /* lines from the block */
- field[j][i] = *p;
-
- field[j][i] = '\0'; /* need this in case i == sizeof(field[j]) */
- /* should probably handle it better, though */
- if (*p)
- p++; /* need to get past the ',' */
- else
- break; /* unless it's '\0', then break */
- }
-
- printf( "(%s)\n(%s)\n(%s)\n(%s)\n", field[0], field[1],
- field[2], field[3]);
-
- return 0;
- }
-
- The possibility of parsed segment being too long for sizeof(field[0]) should
- be handled a bit better. This version of the code will cause unexpected
- results, if it happens.
-
- --
- John R Buchan -:|:- Looking for that elusive FAQ? ftp to:
- jatmon@mail.iag.net -:|:- rtfm.mit.edu /pub/usenet-by-group/....
-
-